package com.jluzh10.learning.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jluzh10.learning.domain.Answer;
import com.jluzh10.learning.domain.Question;
import com.jluzh10.learning.domain.User;
import com.jluzh10.learning.service.AnswerService;
import com.jluzh10.learning.utils.ResponseData;
import com.jluzh10.learning.utils.qiniu.QiniuUtil;
import com.jluzh10.learning.web.converter.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * @author cj
 * @date 5/25/2019
 */

@Controller
@RequestMapping("answer")
@ResponseBody
public class AnswerController {

    private final AnswerService answerService;


    @Autowired
    public AnswerController(AnswerService answerService) {

        this.answerService = answerService;
    }

    /**
     * 新增一个回答
     */
    @RequestMapping("add")
    public ResponseData addAnswer(@LoginUser User user, Answer answer) {

        if(user!=null){
            answer.setCreateTime(new Date());//设置发表时间
            answer.setUserId(user.getId());//设置回答者id
            int i = answerService.addAnswer(answer);//插入回答
            if(i>0){
                return new ResponseData().success("回答成功");//插入回答成功 调用另一个controller显示查询
            } else {
                return new ResponseData().fail("回答失败");//插入回答失败
            }

        } else {
            //跳转到登陆页面
            return new ResponseData().redirect("尚未登陆");
        }
    }

    /**
     * 查询当前问题对应的回答
     * @return
     * @param questionId 问题id
     * @param limit 每页显示数量
     * @param offset 页码
     */
    @RequestMapping(value = "/{answerId}",method = RequestMethod.GET )
    public ResponseData searchAnswer(@PathVariable(value = "answerId") Integer questionId,
                                     @RequestParam(name="limit")int limit,
                                     @RequestParam(name="offset")int offset){
        PageHelper.startPage(offset,limit);
        List<Answer> la = answerService.searchAnswersService(questionId);
        //la.isEmpty()判断集合中是否有元素,la==null判断la是否已经new出来了，不是判断里面是否有元素
        if(la!=null&&!la.isEmpty()){
            PageInfo<Answer> pageInfo = new PageInfo<Answer>(la);
            return new ResponseData().success("回答不为空").data(pageInfo);
        } else {
            return new ResponseData().fail("回答为空");
        }
    }
}
